package net.sunofbeach.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.sunofbeach.blog.mapper.CommentMapper;
import net.sunofbeach.blog.pojo.Comment;
import net.sunofbeach.blog.pojo.User;
import net.sunofbeach.blog.response.Result;
import net.sunofbeach.blog.response.ResultEnum;
import net.sunofbeach.blog.service.CommentService;
import net.sunofbeach.blog.service.UserService;
import net.sunofbeach.blog.utils.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Bing
 * @since 2021-11-24
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Resource
    private UserService userService;

    /**
     * 根据文章ID查询评论列表
     *
     * @param pageParam
     * @param articleId
     * @return
     */
    @Override
    public IPage<Comment> selectPage(Page<Comment> pageParam, String articleId) {

        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(articleId)) {
            wrapper.eq(Comment::getArticleId, articleId);
        }
        return baseMapper.selectPage(pageParam, wrapper);
    }


    /**
     * 根据评论ID删除评论
     *
     * @param commentId
     * @return
     */
    @Override
    public Result removeByCommentId(String commentId) {
        // 检查用户角色
        User user = userService.checkSobUser();
        if (user == null) {
            return Result.build(null, ResultEnum.ACCOUNT_NOT_LOGIN);
        }
        // 找出评论，比对用户权限
        Comment comment = baseMapper.selectById(commentId);
        if (comment == null) {
            return Result.fail().message("评论不存在");
        }
        // 如果当前登录用户为当前评论发表者 或 管理员，可以删除评论
        if (user.getId().equals(comment.getUserId()) || Constants.User.ROLE_ADMIN.equals(user.getRole())) {
            baseMapper.deleteById(commentId);
            return Result.ok().message("评论删除成功");
        }
        // 否则，权限不足，请联系管理员
        return Result.build(null, ResultEnum.PERMISSION_DENIED);
    }

}
